let websocket;
let isOpen = false;
let wsMessageFunc;

/**
 *
 * @returns {boolean} true表示创建成功，false表示之前已经创建过，创建失败
 */
function createWs() {
    if (!websocket) {
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://" + window.location.host + "/ws/asset");
        } else {
            alert('Not support websocket')
        }
        websocket.onclose = closeWs;
        websocket.onmessage = (event) => {
            if (wsMessageFunc) {
                let result = JSON.parse(event.data)
                console.log(result);
                wsMessageFunc(result.action, result, event);
            }
        }
        websocket.onopen = () => {
            isOpen = true;
        }
        return true
    }
    return false;
}

function sendWs(data) {
    if (!websocket) {
        createWs();
        websocket.onopen = () => {
            websocket.send(JSON.stringify(data));
        }
    } else {
        if (isOpen) {
            websocket.send(JSON.stringify(data));
        } else {
            websocket.onopen = () => {
                websocket.send(JSON.stringify(data));
            }
        }
    }
}

function closeWs() {
    if (websocket) {
        websocket.close();
        websocket = undefined;
    }
}
function onWsMessage (func) {
    if (typeof func === 'function') {
        wsMessageFunc = func;
    }
}


//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
window.onbeforeunload = closeWs;
